package com.wontube.smr.web.controller.m;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.wontube.client.extension.utils.StringUtils;
import com.wontube.client.remote.Remoting;
import com.wontube.smr.web.client.m.IWebsiteLinkHandler;
import com.wontube.smr.web.client.model.vo.MWebsiteLinkItems;

/**
 * @author tanggf(2012-6-6)
 * 
 */
@Controller
@RequestMapping("/m")
public class WebsiteLinkController {
	private final static String SYS_ID_ANDROID = "Android";
	private final static String SYS_ID_APAD = "APad";
	private final static String SYS_ID_IPHONE = "IPhone";
	private final static String SYS_ID_IPAD = "IPad";	
	
	@RequestMapping("/links")
	public ModelAndView link_home(
			@RequestParam(value = "hl", required = false) String code, 
			@RequestParam(value="sys", required = false) String sysId,
			HttpServletResponse response) throws IOException {		
		//修正sysId
		sysId = remendSysId(sysId);
		
		//android, android pad使用相同的源.
		String usysId = sysId;
		if(sysId.equals(SYS_ID_APAD)){
			usysId = SYS_ID_ANDROID;
		}
		
		Remoting<IWebsiteLinkHandler> remoting = new Remoting<IWebsiteLinkHandler>();
		IWebsiteLinkHandler handler = remoting.createService(IWebsiteLinkHandler.class);
		//同时纠正countryCode
		MWebsiteLinkItems items = handler.getWebsiteLinkHome(code, usysId);		
		ModelAndView mv = getModelAndView(sysId);
		if(items != null){			
			code = items.getCountryCode();
			mv.addObject("countryCode", code);		
			mv.addObject("items", items);	
			mv.addObject("sysId", sysId);
			
			String defaultInput = "Search or Type in URL";
			if ("CN".equals(code)) {
				response.setContentType("text/html;charset=gbk");
				defaultInput = "搜索视频或输入网址";
			}
			mv.addObject("defaultInput", defaultInput);
		}
		
		return mv;
	}

	private ModelAndView getModelAndView(String sysId) {
		ModelAndView mv = new ModelAndView();
		if(sysId.equals(SYS_ID_IPAD)){
			mv.setViewName("m/ipad");
		}else if(sysId.equals(SYS_ID_IPHONE)){
			mv.setViewName("m/iphone");
		}else{
			mv.setViewName("m/links");
		}
		return mv;
	}
	
	private String remendSysId(String sysId) {	
		if(StringUtils.isNullOrEmpty(sysId)){
			return SYS_ID_ANDROID;
		}
		
		if(sysId.equalsIgnoreCase(SYS_ID_ANDROID)){
			return SYS_ID_ANDROID;
		}
		
		if(sysId.equalsIgnoreCase(SYS_ID_IPAD)){
			return SYS_ID_IPAD;
		}
		
		if(sysId.equalsIgnoreCase(SYS_ID_IPHONE)){
			return SYS_ID_IPHONE;
		}
		
		if(sysId.equalsIgnoreCase(SYS_ID_APAD)){
			return SYS_ID_APAD;
		}
		
		return SYS_ID_ANDROID;
	}
}
